/**
 * @Author: ZFEason
 * @Date: 2023-07-20 13:35:34
 * @LastEditors: ZFEason
 * @LastEditTime: 2023-07-20 17:32:31
 * @FilePath: /ift-economy-network-h5/src/pages/storage-situation/Components/FormUpload.tsx
 * @Description:
 */
import React, { useRef } from "react";
import { tencentCloud } from "../../../utils/upload";
import "./FormUpload.scss";
import { Toast } from "antd-mobile";

const FormUpload: React.FC<any> = ({ data, onUpdate, model, accept }) => {
  const fileRef = useRef(null);

  const upload = async (e: any) => {
    const files = e.currentTarget.files;

    if (!files || !files.length) return;

    if (files.length + (model.imgUrls || []).length > data.maxNum) {
      Toast.show(`最多只能添加${data.maxNum}${data.unit}`);
      return;
    }

    Toast.show("正在上传...");
    const res: any[] = (await tencentCloud({ files })) ?? [];
    const defaultValue = [...(model.defaultValue || []), ...res];
    fileRef.current = null;
    onUpdate(defaultValue, "defaultValue");
    Toast.clear();
  };

  return (
    <>
      <div className={`act-form__upload`}>
        <div className="act-form__upload-button">
          <input
            ref={fileRef}
            type="file"
            accept={accept}
            multiple={false}
            onChange={(e) => upload(e)}
          />
          <span>{data.uploadText}</span>
        </div>
      </div>
    </>
  );
};

export default FormUpload;
